package com.study.manage.mvc.org.collectmoney;

import java.util.HashMap;
import java.util.Map;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import com.study.manage.dal.UserOrganizaRepository;
import com.study.manage.dal.UserRepository;
import com.study.manage.domain.User;
import com.study.manage.domain.UserOrganiza;
import com.study.manage.dto.AjaxResponse;
import com.study.manage.dto.EmailDto;
import com.study.manage.dto.SessionUser;
import com.study.manage.mvc.common.BaseController;

@Controller
@RequestMapping("org/acc")
@Scope("request")
public class CollectionSetController extends BaseController {

    @Autowired
    private UserRepository userRepository;
    
    @Autowired
    private UserOrganizaRepository userOrganizaRepository;

    @RequestMapping(path = "conf", method = RequestMethod.GET)
    public String conf(ModelMap model) {
    	
        SessionUser su = (SessionUser) session.getAttribute("user");
        UserOrganiza userOrganiza = userOrganizaRepository.findOne(su.getUserOrganizaId());
        User regUser = userRepository.findOne(userOrganiza.regUserId);
        User user = userRepository.findOne(su.getId());
        Map<String, Object> map = new HashMap<>();
        map.put("phone", regUser.phone);
        map.put("email", user.email);
        map.put("payAccount", userOrganiza.payAccount);
        map.put("payName", userOrganiza.payName);
        model.put("data", map);
        return "org/acc/conf";
    }

    @ResponseBody
    @RequestMapping(path = "getpaycode", method = RequestMethod.POST)
    public AjaxResponse getPayCode(String phone) throws Exception {
    	
        AjaxResponse ajax = new AjaxResponse(true);
        sendPhoneCode("PAY_CODE_NAME",phone);
        return ajax;
    }

    @ResponseBody
    @RequestMapping(path = "savealipay", method = RequestMethod.POST)
    public AjaxResponse saveAlipay(CollectionSetForm form , ModelMap model) throws Exception {
    	
        AjaxResponse ajax = new AjaxResponse(true);
        SessionUser sessionUser = (SessionUser) session.getAttribute("user");
        String sCode = (String) request.getSession().getAttribute(PAY_CODE_NAME);
        if(EmailDto.checkPhoneCode(sCode,form.getCode())) {
        	return ajax.setMsg("手机验证码错误").setCode("002");
        };
        UserOrganiza organiza = userOrganizaRepository.findOne(sessionUser.getUserOrganizaId());
        organiza.payAccount = form.getPayAccount();
        organiza.payName = form.getPayName();
        userOrganizaRepository.save(organiza);
        return ajax;
    }
}
